package com.findu.activity;

import android.R.drawable;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.ciaapp.sdk.CIAService;
import cn.ciaapp.sdk.VerificationListener;

import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.example.findu.R;


public class SecurityCodeActivity extends Activity implements View.OnClickListener {

    private EditText mCodeEt;
    private String username;
    private  String  pwd   ; 
    private TextView vertifyView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_security_code);
        
        
      /*  Bundle bundle = this.getIntent().getExtras();
  	  username=bundle.getString("username");
  	   pwd=bundle.getString("pwd");  
  	   Log.d("用户名+_密码", username+pwd+"1onCreate");*/

        // 设置下一步按钮的点击事件
        findViewById(R.id.bt_next).setOnClickListener(this);

        // 验证码的输入框
        mCodeEt = (EditText) findViewById(R.id.et_code);
        
        //倒计时
        vertifyView=(TextView) findViewById(R.id.vertifyView);

        TextView tv_hint = (TextView) findViewById(R.id.tv_hint);
        tv_hint.setText("验证码已发送到您输入的手机号码上，隐藏在手机未接来电" + CIAService.getSecurityCode() + "的后四位，请查询并输入验证码。");
        Bundle bundle = this.getIntent().getExtras();
  	  username=bundle.getString("username");
  	   pwd=bundle.getString("pwd");  
  	   Log.d("用户名+_密码", username+pwd+"11111onActivityResult");
  	    //倒计时 
  	    timer.onTick(60000);
  	    timer.start();
    }
    /**
     * 接收传来的参数
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    	/*username=data.getStringExtra("username");
    	   pwd=data.getStringExtra("pwd");  */
    	
    	 Bundle bundle = this.getIntent().getExtras();
    	  username=bundle.getString("username");
    	   pwd=bundle.getString("pwd");  
    	   //Log.d("用户名+_密码", username+pwd+"2onActivityResult");
    }
    
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 页面关闭的时候取消验证，如果有当前有验证请求就取消验证
        CIAService.cancelVerification();
    }
   
    @Override
    public void onClick(View v) {
        // 点击下一步，校验验证码的正确性
        // 获取用户输入的验证码
        String code = mCodeEt.getText().toString();
        // 校验验证码
        CIAService.verifySecurityCode(code, new VerificationListener() {
            /**
             * 校验结果回调
             * @param status        验证状态码
             * @param msg           验证状态的描述
             * @param transId       当前验证请求的流水号，服务器可以根据流水号查询验证的状态
             */
            @Override
            public void onStateChange(int status, String msg, String transId) {
            	final ProgressDialog progressDialog=new ProgressDialog(SecurityCodeActivity.this);
                /**
                 * status 是返回的状态码，CIAService包含了一些常量
                 * @see CIAService.VERIFICATION_SUCCESS    验证成功
                 * @see CIAService.SECURITY_CODE_WRONG 验证码输入错误
                 * @see CIAService.SECURITY_CODE_EXPIRED   验证码失效，需要重新验证
                 * @see CIAService.SECURITY_CODE_EXPIRED_INPUT_OVERRUN  验证码输入错误次数超限(3次)，需要重新验证
                 */

                switch (status) {
                    case CIAService.VERIFICATION_SUCCESS: // 验证成功
                        //showToast("不是本机也验证成功啦*_*");
                        // TODO 进入下一步业务逻辑
                        // TODO 注册到环信
                    	Log.d("用户名+_密码", username+pwd+"2onActivityResult");
                        
                        new Thread(new Runnable() {
            				public void run() {
            					try {
            						 
            						
            						// 调用sdk注册方法
            						Log.d("下一步手机值",username+"======"+pwd+"不是本机验证通过后怎么传值,还是再调用一次注册的环信方法");
            						EMChatManager.getInstance().createAccountOnServer(username, pwd);
            						
            						
            						runOnUiThread(new Runnable() {
            							public void run() {
            								if (!SecurityCodeActivity.this.isFinishing())
            									progressDialog.dismiss();
            								// TODO  保存用户名,注册成功后跳转到登录页面 
            						  	    //DemoHelper.getInstance().setCurrentUserName(username);
            							    // PreferenceManager.getInstance().setCurrentUserName(username);
            								//Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), 0).show();
            								 Toast.makeText(SecurityCodeActivity.this, getResources().getString(R.string.Registered_successfully), 0).show();
            								//back();
            								 Log.d("跳", "***调到登录页面******");
            								 Log.d("跳2",username+"======"+pwd+"不是本机验证通过后怎么传值,还是再调用一次注册的环信方法");
            								 //打开登录页面,闪退 LoginActivity.start(SecurityCodeActivity.this); 
            							 
            								  
            								//打开登录页面,已经放到back方法里面
            								// startActivity(new Intent(getApplicationContext(), LoginActivity.class));//OK
            								 backLoginActivity();
            							}
            						});
            					} catch (final EaseMobException e) {
            						runOnUiThread(new Runnable() {
            							public void run() {
            								if (!SecurityCodeActivity.this.isFinishing())
            								//	pd.dismiss();
            							   progressDialog.dismiss();
            								int errorCode=e.getErrorCode();
            								if(errorCode==EMError.NONETWORK_ERROR){
            									Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            								}else if(errorCode == EMError.USER_ALREADY_EXISTS){
            									//用户存在!!!
            									Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
            									//调到注册页面
            									 startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
            									//关闭当前页面
            									 finish();
            								}else if(errorCode == EMError.UNAUTHORIZED){
            									Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
            								}else if(errorCode == EMError.ILLEGAL_USER_NAME){
            								    Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
            								}else{
            									Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
            								}
            							}
            						});
            					}
            				}
            			}).start(); 
                        finish();
                        break;
                    case CIAService.SECURITY_CODE_WRONG: // 验证码输入错误
                        showToast("验证码错误");
                        break;
                    case CIAService.SECURITY_CODE_EXPIRED:  // 验证码失效，需要重新验证
                    	startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
                        showToast("验证码失效，请重新验证");
                        finish();
                        break;
                    case CIAService.SECURITY_CODE_EXPIRED_INPUT_OVERRUN:    // 验证码输入错误次数过多(3次)，需要重新验证
                        showToast("验证码输入错误超过3次，请重新验证");
                        //调到注册页面 ,重新验证要跳到注册页面
                        startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
                        finish();
                       
                        break;
                }
            }
        });
        
        /*
         * 点击重新获取验证码,由于下一步你没有判断其ID 你点击vertifyView时,也同样会执行下一步
         * 
         */
        switch (v.getId()){
        
        case R.id.vertifyView:
    	   
    	   Toast.makeText(SecurityCodeActivity.this , "重新调用打电话的方法", 0).show();
    	   
    	   //new RegisterActivity().verification(username);
    	   
        break;
        }
        
        
    }

    /**
     * Toast提示
     *
     * @param txt
     */
    private void showToast(String txt) {

        Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
    }
    
    public static void start(Context context) {
		Intent intent = new Intent(context, SecurityCodeActivity.class);
		context.startActivity(intent);
	}
    public void backLoginActivity() {

		Intent intent = new Intent();
		//第二个参数是要跳转的页面的全路径  
		intent.setClassName( getApplicationContext(), "com.findu.activity.LoginActivity" );
		 intent.putExtra("data_return",username);
		
		 //不需要接收组件的返回值，就可以直接这样激活了
		 // startActivity(intent);
		
		  // setResult(RESULT_OK, intent);
		
		    //需要接收返回结果。注意返回的结果码
		      startActivityForResult(intent, 100);

		  finish(); 
		// 关闭当前页面  

	}
    
   /**
    * @author ggj
    * 倒计时
    * http://blog.csdn.net/freesonhp/article/details/25904047
    */
	private CountDownTimer timer = new CountDownTimer(60000, 1000) {

		@Override
		/*public void onTick(long millisUntilFinished) {*/
			public void onTick(long millisUntilFinished) {
			vertifyView.setText((millisUntilFinished / 1000) + "秒后可重发");
		}

		@Override
		public void onFinish() {
			vertifyView.setEnabled(true);
			vertifyView.setText("重新获取验证码");
			
			//添加事件
			//vertifyView.setOnClickListener(SecurityCodeActivity.this);
			//重新设置颜色
			//vertifyView.setBackgroundColor(TRIM_MEMORY_COMPLETE);
			//vertifyView.setBackgroundColor(Color.parseColor("#F5F5DC"));//米黄 FCEEAA
			//TODO 下一步变灰
		
		}
	};
	   
}
